// bin2c.cc - converts binary (read: any) files into c arrays in a header file

/*
   Copyright 2006 Corey Tabaka

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char ** argv) {
	if (argc != 2) {
		printf("Usage: %s <binary file>\n", argv[0]);
		exit(-1);
	}
	
	char dest[2048];
	
	strncpy(dest, argv[1], sizeof(dest));
	strcat(dest, ".h");
	
	FILE *fin = fopen(argv[1], "rb");
	
	if (!fin) {
		fprintf(stderr, "Error opening source file %s\n", argv[1]);
		exit(-2);
	}
	
	FILE *fout = fopen(dest, "w");
	
	if (!fout) {
		fprintf(stderr, "Error opening destination file %s\n", dest);
		exit(-3);
	}
	
	fprintf(fout, "#ifndef DATA_ARRAY_NAME\n"
		"#define DATA_ARRAY_NAME data_array\n"
		"#endif\n"
		"#ifndef DATA_ARRAY_ATTR\n"
		"#define DATA_ARRAY_ATTR \n"
		"#endif\n"
		"const char DATA_ARRAY_NAME [] DATA_ARRAY_ATTR = {\n"
	);
	
	unsigned char buffer;
	unsigned int count = 0;
	
	while(fread(&buffer, sizeof(buffer), 1, fin)) {
		fprintf(fout, "0x%02x, ", buffer);
		
		if (++count % 13 == 0) {
			fprintf(fout, "\n");
		}
	}
	
	fprintf(fout, "\n};\n");
	
	printf("Read %d bytes\n", count);
	
	fclose(fin);
	fclose(fout);
	
	return 0;
}
